using System;
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// 全局工具
/// </summary>
public static partial class HFGlobalUtility
{
    /// <summary>
    /// 内存Stopwatch
    /// </summary>
    class MemoryStopwatch
    {
        /// <summary>
        /// TotalMemory Stopwatch
        /// </summary>
        Stopwatch mTotalMemoryStopwatch = new Stopwatch();
        /// <summary>
        /// 开始时内存
        /// </summary>
        long mStartTotalMemory = 0;
        /// <summary>
        /// 结束时内存
        /// </summary>
        long mEndTotalMemory = 0;
        /// <summary>
        /// 统计名称
        /// </summary>
        string mName = string.Empty;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_name">统计名称</param>
        public MemoryStopwatch(string _name)
        {
            mName = _name;
        }
        /// <summary>
        /// 开始统计内存
        /// </summary>
        public void StartTotalMemory()
        {
            mTotalMemoryStopwatch.Restart();
            mStartTotalMemory = GC.GetTotalMemory(false);
        }
        /// <summary>
        /// 结束统计内存
        /// </summary>
        /// <returns></returns>
        public string EndTotalMemory()
        {
            mTotalMemoryStopwatch.Stop();
            mEndTotalMemory = GC.GetTotalMemory(false);
            return $"【{mName}】TotalMemory：{(mEndTotalMemory - mStartTotalMemory).HFToRAMChar()}，Time：{mTotalMemoryStopwatch.ElapsedMilliseconds} ms";
        }
    }

    /// <summary>
    /// MemoryStopwatch映射
    /// </summary>
    static Dictionary<string, MemoryStopwatch> mMemoryStopwatchMaping = new Dictionary<string, MemoryStopwatch>();
  
    /// <summary>
    /// 开始统计TotalMemory
    /// </summary>
    /// <param name="_name">统计名称</param>
    public static void StartTotalMemory(string _name)
    {
#if UNITY_EDITOR
        MemoryStopwatch watch = null;
        if (!mMemoryStopwatchMaping.TryGetValue(_name, out watch))
        {
            watch = new MemoryStopwatch(_name);
            mMemoryStopwatchMaping.Add(_name, watch);
        }
        watch.StartTotalMemory();
#endif
    }

    /// <summary>
    /// 结束统计TotalMemory
    /// </summary>
    /// <param name="_name">统计名称</param>
    public static string EndTotalMemory(string _name)
    {
        string result = $"EndTotalMemory is used in UNITY_EDITOR";
#if UNITY_EDITOR
        MemoryStopwatch watch = null;
        if (mMemoryStopwatchMaping.TryGetValue(_name, out watch))
        {
            result = watch.EndTotalMemory();
        }
#endif
        return result;
    }
}
